package it.progettoso.thread;

import it.progettoso.utility.DBConnection;
import android.content.Context;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class ControlSimThread implements Runnable{
	private String phone="";
	private String mess="";
	private Context c;
	DBConnection db=null;

	public ControlSimThread(Context context,String phone) {
		this.c=context;
		this.phone=phone;
		db = new DBConnection(context);
	}

	@Override
	public void run() {
		controlloSM(c);
	}

	private void controlloSM(Context c){
		TelephonyManager mtm= (TelephonyManager)c.getSystemService(Context.TELEPHONY_SERVICE);
		String serialNumber=mtm.getSimSerialNumber();
		String mySerialNumber=null;

		if(serialNumber==null){
			mess="NUMERO ATTUALE...Validazione anomala!";
			sendSMS(phone,mess);
			return;
		}
		try{
			if(db==null)
				return;
			if(db.open()){
				mySerialNumber = db.readData(DBConnection.SIM_SERIAL_NUMBER);
				if(mySerialNumber == null || mySerialNumber==""){
					db.insertData(DBConnection.SIM_SERIAL_NUMBER, serialNumber);
				}else{
					if(!isEqualSerial(serialNumber,mySerialNumber)){
						mess="NUOVO NUMERO...Scheda SIM sostituita!!!";
						sendSMS(phone,mess);
						db.updateData(DBConnection.SIM_SERIAL_NUMBER, serialNumber);
					}
				}
				db.close();
			}
		}catch (Exception e) {
			Toast.makeText(c, "ECCEZIONE:" +e.fillInStackTrace(), Toast.LENGTH_SHORT).show();
		}
	}
	private boolean isEqualSerial(String serialNumber,String mySerialNumber){
		if(serialNumber.equals(mySerialNumber))
			return true;
		else
			return false;		
	}
	
	//---sends a SMS message to another device---
	public void sendSMS(String phoneNumber, String message){      
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, null, null);               
	}

}
